package org.docmanagement.data;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.docmanagement.commons.Constants;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;

@Entity
@Table(name="CATEGORIES")
@Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Category extends Id implements Serializable {

	private static final long serialVersionUID = 1L;

	private String name = null;
//	private Integer parentId = null;
	private Category parent = null;

	public Category() {
		super();
	}

	@javax.persistence.Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	public Integer getId() {
		return super.getId();
	}

	@Column(name="LABEL")
	public String getName() {
		return name;
	}

//	@Column(name="PARENT_ID")//, updatable=false, insertable=false)
	@Transient
	public Integer getParentId() {
		if (parent != null) {
			return parent.getId();
		}
		return null;
	}

	@ManyToOne
	@JoinColumn(name="PARENT_ID")
	public Category getParent() {
		return parent;
	}

	@Transient
	public String getFullname() {
		String result = getName();
		Category current = this;
		while (current.getParent() != null) {
			current = current.getParent();
			result = current.getName() + Constants.CATEGORY_SEPARATOR + result;
		}
		return result;
	}

	public void setName(String pName) {
		name = pName;
	}

//	public void setParentId(Integer id) {
//		parentId = id;
//	}

	public void setParent(Category pParent) {
		parent = pParent;
//		if (pParent == null)
//			setParentId(null);
//		else
//			setParentId(pParent.getId());
	}

	public String toString() {
		StringBuffer s = new StringBuffer();
		s.append(name).append(" (").append(getId());
		s.append(", parentId: ").append(getParentId());
		s.append(')');
		return s.toString();
	}

	public boolean equals(Object obj) {
		if (obj instanceof Category)
			return getId().equals(((Category) obj).getId());
		return false;
	}

	public int hashCode() {
		return 17 * getId().hashCode();
	}
}
